package com.wang.mall.controller;

import com.wang.mall.model.LoginParams;
import com.wang.mall.model.LoginResult;
import com.wang.mall.model.R;
import com.wang.mall.service.SysCaptchaService;
import com.wang.mall.service.SysLoginService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 系统用户登录
 */
@RestController
@RequestMapping("/sys")
public class SysUserLoginController {


    @Autowired
    private SysLoginService sysLoginService;


    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    private SysCaptchaService sysCaptchaService;


    /**
     * 验证码
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    @PostMapping("/login")
    public R sysLogin(@RequestBody LoginParams loginParams) {
        boolean validate = sysCaptchaService.validate(loginParams.getUuid(), loginParams.getCaptcha());
        if (!validate) {
            return R.fail("验证码不正确");
        }

        LoginResult loginResult = sysLoginService.login(loginParams.getUsername(), loginParams.getPassword());
        return R.ok(loginResult);
    }


    @PostMapping("/logout")
    public R logout(HttpServletRequest request) {
        new SecurityContextLogoutHandler().logout(request, null, null);
        String authorization = request.getHeader("Authorization");
        String replace = authorization.replace("bearer ", "");
        Boolean delete = redisTemplate.delete(replace);
        return R.ok("退出成功");
    }

}
